package cn.neusoft.customer.controller;

import cn.neusoft.customer.common.ResponseEntity;
import cn.neusoft.customer.service.OrderService;
import cn.neusoft.customer.service.OrderInfoService;
import cn.neusoft.customer.service.SpecialOrderService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import net.minidev.json.JSONObject;
import org.example.entity.*;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
@CrossOrigin
@Slf4j
public class OrderController {
    @Resource
    OrderService orderService;

    @Resource
    SpecialOrderService specialOrderService;

    @Resource
    OrderInfoService orderInfoService;

    //ture有订单，false没有订单
    @PostMapping("/hasOrderRecord/{customerName}")
    public ResponseEntity<Boolean> hasPurchaseRecord(@PathVariable String customerName) {
        try {
            QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
            orderQueryWrapper.eq("customerName", customerName);
            int numOfOrder = orderService.count(orderQueryWrapper);
            return ResponseEntity.success(numOfOrder != 0);
        } catch (Exception e) {
            return ResponseEntity.error("系统错误：" + e.getMessage());
        }
    }

    @PostMapping("/record/{customerName}")
    public ResponseEntity<Map<String, Object>> customerRecord(@PathVariable String customerName) {
        ResponseEntity<Map<String, Object>> httpResponse = new ResponseEntity<>();
        try {
            QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
            orderQueryWrapper.eq("customerName", customerName);
            List<Order> orderList = orderService.list(orderQueryWrapper);
            Map<String, Object> map = new HashMap<>();
            map.put("order", orderList);
            httpResponse.setData(map);
            httpResponse.setCode(1);
        } catch (Exception e) {
            return ResponseEntity.error("系统错误：" + e.getMessage());
        }
        return httpResponse;
    }

    @PostMapping("/add")
    public ResponseEntity<String> addOrder(@RequestBody OrderDTO orderDTO) {
        UUID uuid = UUID.nameUUIDFromBytes(orderDTO.toString().getBytes());
        String orderId = uuid.toString(); // 将 UUID 转换为字符串
        try {
            orderDTO.getOrder().setOrderId(orderId);
            orderDTO.getOrder().setOrderType("新订");
            orderDTO.getOrderInfo().setOrderId(orderId);
            orderDTO.getOrderInfo().setCreateTime(LocalDateTime.now());
            if (orderService.save(orderDTO.getOrder())) {
                System.out.println(orderDTO.getOrderInfo());
                if (orderInfoService.save(orderDTO.getOrderInfo())) {
                    return ResponseEntity.success("添加成功");
                } else {
                    orderService.removeById(orderId);
                }
            }
            return ResponseEntity.error("添加失败");
        } catch (Exception e) {
            orderService.removeById(orderId);
            return ResponseEntity.error("系统错误：" + e.getMessage());
        }
    }

    @PostMapping("/specialOrder")
    public ResponseEntity<String> specialOrder(@RequestBody JSONObject params) {
        UUID uuid = UUID.nameUUIDFromBytes(params.toString().getBytes());
        String orderId = uuid.toString(); // 将 UUID 转换为字符串
        try {
            String originalId = params.getAsString("originalId:");
            if (orderService.getById(originalId) == null &&
                    specialOrderService.getById(originalId) == null) {
                return ResponseEntity.error("无法找到原订单");
            }
            QueryWrapper<SpecialOrder> specialOrderQueryWrapper = new QueryWrapper<>();
            specialOrderQueryWrapper.eq("original_id", originalId);
            if (specialOrderService.getOne(specialOrderQueryWrapper) != null) {
                return ResponseEntity.error("该订单已经申请处理，如果需要再次处理，请选取处理后的订单再申请处理");
            }
            UpdateWrapper<Order> orderUpdateWrapper = new UpdateWrapper<>();
            SpecialOrder specialOrder = new SpecialOrder();
            specialOrder.setOriginalId(originalId);
            orderUpdateWrapper.eq("orderId", originalId);
            orderUpdateWrapper.set("orderId", orderId);
            orderUpdateWrapper.set("orderType", params.getAsString("orderType"));
            orderService.update(orderUpdateWrapper);
            specialOrder.setReason(params.getAsString("reason"));
            specialOrder.setOrderId(orderId);
            specialOrder.setProcessDate(LocalDate.now());
            specialOrder.setCreateTime(LocalDateTime.now());
            if (specialOrderService.save(specialOrder)) {
                return ResponseEntity.success("添加成功");
            }
            return ResponseEntity.error("添加失败");
        } catch (Exception e) {
            return ResponseEntity.error("系统错误：" + e.getMessage());
        }
    }

    @PostMapping("/getOne")
    public ResponseEntity<Order> getOneOrder(@RequestBody JSONObject params) {
        ResponseEntity<Order> httpResponse = new ResponseEntity<>();
        try {
            String orderId = params.getAsString("orderId");
            String id = orderId;
            SpecialOrder specialOrder = specialOrderService.getById(orderId);
            while (specialOrder != null) {
                orderId = specialOrder.getOriginalId();
                specialOrder = specialOrderService.getById(orderId);
            }
            Order order = orderService.getById(orderId);
            order.setOrderId(id);
            httpResponse.setData(order);
            httpResponse.setCode(1);
        } catch (Exception e) {
            return ResponseEntity.error("系统错误：" + e.getMessage());
        }
        return httpResponse;
    }

    @GetMapping("/workRecord/{operatorName}")
    public ResponseEntity<Record> workRecord(@PathVariable String operatorName,
                                             @RequestParam("start") @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") String start,
                                             @RequestParam("end") @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") String end) {
        ResponseEntity<Record> httpResponse = new ResponseEntity<>();
        Record record = new Record(operatorName);
        try {
            // 转换为LocalDateTime类型
            LocalDateTime startDate = LocalDateTime.parse(start);
            LocalDateTime endDate = LocalDateTime.parse(end);
            record.setOperator(operatorName);
            QueryWrapper<OrderInfo> orderInfoQueryWrapper = new QueryWrapper<>();
            orderInfoQueryWrapper.between("create_time", startDate, endDate);
            orderInfoQueryWrapper.eq("operator", operatorName).select("order_id");
            List<String> orderIdList = orderInfoService.list(orderInfoQueryWrapper).stream()
                    .map(OrderInfo::getOrderId)
                    .collect(Collectors.toList());
            if (orderIdList.size() > 0) {
                List<Order> orderList = orderService.listByIds(orderIdList);
                for (Order order :
                        orderList) {
                    QueryWrapper<SpecialOrder> specialOrderQueryWrapper = new QueryWrapper<>();
                    specialOrderQueryWrapper.eq("original_id", order.getOrderId());
                    Info[] infos = record.getInfos();
                    int category = order.getOrderType().equals("新订")?0:order.getOrderType().equals("退订")?1:order.getOrderType().equals("换货")?2:3;
                    infos[category].setQuantity(infos[category].getQuantity() + order.getProductNum());
                    infos[category].setCount(infos[category].getCount() + 1);
                    double income = order.getProductPrice() * order.getProductNum();
                    if (category == 2 || category == 0) {
                        record.setIncome(record.getIncome() + income);
                    }
                    infos[category].setAmount(infos[category].getAmount() + income);
                }
                record.setIncome(record.getInfos()[0].getAmount() + record.getInfos()[2].getAmount());
            }
            httpResponse.setData(record);
            httpResponse.setCode(1);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResponseEntity.error("系统错误" + e.getMessage());
        }
        return httpResponse;
    }

}
